package edu.sysu.demo.rabbitmq;

import edu.sysu.demo.rabbitmq.data.dao.DealDao;
import edu.sysu.demo.rabbitmq.data.dao.ItemDao;
import edu.sysu.demo.rabbitmq.data.dao.UserDao;
import edu.sysu.demo.rabbitmq.data.entity.Deal;
import edu.sysu.demo.rabbitmq.data.entity.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RabbitListener(queues = {Subscriber.ROUTING_KEY})
public class Subscriber {

  static final String ROUTING_KEY = "cottle.odd";

  private DealDao dealDao;

  private ItemDao itemDao;

  private UserDao userDao;

  @RabbitHandler
  public void dequeue(Deal deal) {
    log.info("Received message : {}", deal);

    deal.setBuyer(userDao.save(deal.getBuyer()));
    deal.setSeller(userDao.save(deal.getSeller()));

    Item found = itemDao.findByName(deal.getItem().getName());

    if (found != null) {
      deal.setItem(found);
    } else {
      deal.setItem(itemDao.save(deal.getItem()));
    }

    dealDao.save(deal);
  }

  @Autowired
  public void setDealDao(DealDao dealDao) {
    this.dealDao = dealDao;
  }

  @Autowired
  public void setItemDao(ItemDao itemDao) {
    this.itemDao = itemDao;
  }

  @Autowired
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }
}
